package com.sky.aspect;

import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 *
 * 自定义切面类
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    /**
     * 切入点
     *
     * 不仅满足mapper下面的方法  还要是加上了注解的
     */
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointCut(){}


    /**
     * 前置通知
     */
    @Before("autoFillPointCut()")
        public void autoFill(JoinPoint joinPoint) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        log.info("开始进行公共字段填充......");

        //获取当前被拦截的方法是insert 还是update
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();  //获取连接点的签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获得方法上的注解对象
        OperationType value = annotation.value();//获取是update 还是insert
        //获取被拦截方法参数的实体
        Object[] args = joinPoint.getArgs();
        if(args == null || args.length==0){
            return;
        }
        Object objects = args[0];
        //通过反射 为公共属性进行赋值、
        if (value == OperationType.INSERT){
         //为四个公共字段赋值
            Method setCreateTime = objects.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method setCreateUser = objects.getClass().getDeclaredMethod("setCreateUser", Long.class);
            Method setUpdateTime = objects.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = objects.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            //调用这个方法
            setCreateTime.invoke(objects,LocalDateTime.now());
            setUpdateTime.invoke(objects,LocalDateTime.now());
            setUpdateUser.invoke(objects,BaseContext.getCurrentId());
            setCreateUser.invoke(objects,BaseContext.getCurrentId());
        } else if (value == OperationType.UPDATE) {
         //为两个公共字段赋值
            Method setUpdateTime = objects.getClass().getDeclaredMethod("setUpdateTime", LocalDateTime.class);
            Method setUpdateUser = objects.getClass().getDeclaredMethod("setUpdateUser", Long.class);
            setUpdateUser.invoke(objects,BaseContext.getCurrentId());
            setUpdateTime.invoke(objects,LocalDateTime.now());

        }



    }




}
